/**
 * 费用申请模块业务入口
 */
import presetVar from './presetVar';
import React, { Component } from 'react';
import { createPage, base, high, getMultiLang ,pageTo} from 'nc-lightapp-front';
import { tableButtonClick, pageButtonClick, afterEvent, beforeEvent, refreshButtonClick } from './events';
import initTemplate, {routeChange} from './initTemplate';
import { getAfterEventParams } from 'ssccommon/utils/formulaUtils';
import pubMessage from 'ssccommon/utils/pubMessage';
import AdjustRelationSearch from '../../adjustRelation/list/adjustRelationSearch';
import Inspection from 'epmp/exports/components/Inspection';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import NCUploader from 'uap/common/components/NCUploader';
import attachments from 'uap/common/components/getAttachmentInfo';
import ApprovalTrans from 'uap/common/components/approvalTrans';
import { setTable } from 'ssccommon/utils/setComponentUsed'
import BillApprove from 'uap/common/components/BillApprove';

const { getAttachments, getAttachmentsInfo } = attachments;
let { NCModal } = base;
import {
    BillStyle,
    BillHead,
    BillBody,
    Form,
    CardTable,
    ButtonGroup
} from 'ssccommon/components/bill';

import { EditTable } from 'ssccommon/components/table';
import './index.less';

const pageButton = presetVar.pageButton;
const body1 = presetVar.body.body1;
const head1 = presetVar.head.head1;

window.assingUsers = [];
window.sureAssign = false;//确定指派
window.assignBillId = '';//有指派的情况下，第一次点保存提交实际保存成功的单据pk

// window.billinfo = {
//     tzd_billid: '',
//     tzd_billno: '',
//     tzd_tradetype: ''
// };

class Adjustment extends Component {

    constructor(props) {
        super(props);
        props.use.form('head');
        setTable(props, 'linkrelationbill');
        /* if (NODE_ENV == 'development') {
            window.NODE_ENV = 'development';
        } */
        this.state = {
            showApprovePanel: false,
            showUploader: false,
            ShowApproveDetail: false,
            billtype: '',
            billId: '',
            compositedata: '',
            compositedisplay: '',
            sourceData: null,
            showLinkBudget: false,
            title: '',
            showRelationModal: false,
            linkRelationBillModal: false,
            uploaderBtnDisable: false
        }
        this.billId = props.getUrlParam('billid');
        this.pubMessage = new pubMessage(props);

        initTemplate.call(this, props);
        this.haedLayout = function (multiLang, btnModalConfig, head1) {
            return (

                <BillHead
                    // "201102TZFY-0001": "费用调整单"
                    title={this.state.title}
                    refreshButtonEvent={refreshButtonClick.bind(this)}
                >
                    <ButtonGroup
                        areaId={presetVar.head.head2}
                        buttonEvent={pageButtonClick.bind(this)}
                        modalConfig={btnModalConfig}
                        sagasButtonVisible={true}
                    />

                    <Form
                        areaId={head1}
                        onAfterEvent={afterEvent.bind(this)} //表体编辑后事件
                    />
                </BillHead>
            )
        }

        // TOP NCCLOUD-61317 增加公式编辑后联动 chengwebc ADD
        props.setRelationAfterEventCallBack && props.setRelationAfterEventCallBack((props, changedField, changedArea, oldCard, newCard, index, rowId) => {
            let params = getAfterEventParams(props, changedField, changedArea, oldCard, newCard, index, rowId);
            params.map((one) => {
                afterEvent.call(this, props, one.moduleId, one.key, one.value, one.changedrows, one.index)
            })
        });
        // BTM NCCLOUD-61317 增加公式编辑后联动 chengwebc

        //关联成功后需要关闭modal
        window.closeRelation = () => {
            this.setState({
                showRelationModal: false
            })
        }
    }

    componentDidMount() {
        this.props.setHashChangeCallback(() => {
            routeChange.call(this, this.props);
      })
    }
    componentWillMount() {
        window.onbeforeunload = () => {
            let status = this.props.getUrlParam("status");
            if (status == 'edit' || status == 'add') {
                return ''/* 国际化处理： 确定要离开吗？*/
            }
        }
    }
    cancel() {
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info) {
        this.setState({
            showLinkBudget: false
        })
    }
    closeApprove = () => {
        this.setState({
            ShowApproveDetail: false
        })
    }
    getAssginUser = (value) => {
        window.assingUsers = value;
        window.sureAssign = true;
        pageButtonClick.call(this)[pageButton.Submit]();
        window.assignBillId = '';
    }

    turnOff() {
        this.setState({
            compositedisplay: false
        });
        window.sureAssign = false;
        window.assingUsers = [];
        let props = this.props;
        let billid = window.assignBillId;
        if (!billid) {
            let billdata = props.createExtCardData(presetVar.nccPageCode, head1, [body1]);
            let headValues = billdata.head[head1].rows[0].values;
            billid = headValues.pk_jkbx.value;
        }
        pageTo.specialLinkTo(location.pathname, {
            status: presetVar.status.browse,
            id: billid,
            scene: presetVar.scene
        })
        routeChange.call(this, this.props)

    }
    cancel() {
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info) {
        this.setState({
            showLinkBudget: false
        })
    }
    closeRelation() {
        this.setState({
            showRelationModal: false
        })
    }
    uploaderOnHide() {
        this.setState({ showUploader: false });
        let multiLang = this.props.MutiInit.getIntl(2011);
        getAttachments(presetVar.openBillId).then((count) => {
            this.props.button.setButtonTitle('File', multiLang&&multiLang.get('201102TZFY-0003')/**'附件'**/ + ' ' + String(count) + ' ');
        })
    }

    setRelationChecked = (data, relationProps) => {
        let relatedPks = [];
        data.grid && data.grid.rplist && data.grid.rplist.rows && data.grid.rplist.rows.forEach((row) => {
            let relatePk = row.rowId ? row.rowId : row.values.pk_bill && row.values.pk_bill.value;
            relatedPks.push(relatePk);
        })
        relationProps.transferTable.setTheCheckRows(window.presetVar.list, relatedPks);
    }
    // 云原生环境
    renderErrorCenterState () {
        const { props } = this
        const status = props.form.getFormItemsValue(head1, 'saga_status')
        if (!status || status.value !== '1') return null;

        this.props.button.toggleErrorStatus('head',{
            isError: true
        })
        window.___props = props
        const param = {
            headBtnAreaCode: 'head',
            formAreaCode: head1,
            billtype: status.value,
            billpkname: 'pk_jkbx',
            dataSource: 'erm.expenseaccount.adjustment.card'
        }
        return props.socket.connectMesg(param)
    }

    render() {
        const { table } = this.props;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let { createSimpleTable } = table;
        let btnModalConfig = {
            [pageButton.Delete]: {
                // "2011-0004": "删除",
                // "2011-0005": "确认删除该单据吗？"
                title: multiLang && multiLang.get('2011-0004'),
                content: multiLang && multiLang.get('2011-0005')
            },
            [pageButton.Invalid]: {
                // "2011-0009": "作废",
                // "2011-0010": "确认作废该单据吗？"
                title: multiLang && multiLang.get('2011-0009'),
                content: multiLang && multiLang.get('2011-0010')
            },
            [pageButton.billEnable]: {
                // "2011-0011": "重启",
                // "2011-0012": "确认重启该单据吗？"
                title: multiLang && multiLang.get('2011-0011'),
                content: multiLang && multiLang.get('2011-0012')
            },
            [pageButton.billClose]: {
                // "2011-0007": "关闭",
                // "2011-0013": "确认关闭该单据吗？",
                title: multiLang && multiLang.get('2011-0007'),
                content: multiLang && multiLang.get('2011-0013')
            }
        }
        return (

            <div style={{overflow: 'scroll'}}>
                {this.renderErrorCenterState()}
                <BillStyle
                    {...this.props}
                >
                    {this.haedLayout(multiLang, btnModalConfig, head1)}

                    <BillBody>

                        <CardTable
                            // "201102TZFY-0002": "费用申请单明细",
                            title={multiLang && multiLang.get('201102TZFY-0002')} //表体表体
                            areaId={body1}       //表体区域id
                            totalItemCode="assume_amount"   //表体的统计字段
                            modelSave={pageButtonClick.call(this)[pageButton.Save]} //卡片上的整单保存按钮
                            onAfterEvent={afterEvent.bind(this)} //表体编辑后事件
                            onBeforeEvent={beforeEvent.bind(this)}
                            modelDelRow={() => {
                                console.log(888);
                            }}
                        >
                            <ButtonGroup
                                // areaId={body1 + "_card_body"}  //按照默认区域规则配置，这里可以不配置
                                buttonEvent={tableButtonClick.bind(this)} //仅使用默认按钮，这里也可以不配置
                            />
                        </CardTable>

                        <div>
                            {this.state.showUploader && < NCUploader
                                disableButton={this.state.uploaderBtnDisable}
                                billId={presetVar.openBillId}
                                targrt={null}
                                placement={'bottom'}
                                onHide={this.uploaderOnHide.bind(this)}
                            />
                            }
                        </div>
                        <div>
                            <ApproveDetail
                                show={this.state.ShowApproveDetail}
                                close={this.closeApprove}
                                billtype={this.state.billtype}
                                billid={this.state.billId}
                            />
                        </div>

                        <BillApprove
                            show={this.state.showApprovePanel}
                            close={() => this.setState({ showApprovePanel: false })}
                            billtype={presetVar.tradeType}
                            billid={this.billId}
                        />
                        <div>
                            {/*"201102FYYT-0003": "指派",*/}
                            {this.state.compositedisplay ? <ApprovalTrans
                                title={multiLang && multiLang.get('201102FYYT-0003')}
                                data={this.state.compositedata}
                                display={this.state.compositedisplay}
                                getResult={this.getAssginUser}
                                cancel={this.turnOff.bind(this)}
                            /> : ""}

                        </div>
                        <div>
                            <Inspection
                                show={this.state.showLinkBudget}
                                sourceData={this.state.sourceData}
                                cancel={this.cancel.bind(this)}
                                affirm={this.affirm.bind(this)}
                            />
                        </div>
                    </BillBody>
                </BillStyle>

                <NCModal size="xlg"
                    show={
                        this.state.showRelationModal
                    }
                    onHide={
                        this.closeRelation.bind(this)
                    }
                >

                    <NCModal.Header closeButton="true">
                        {/*"201102BCLF-0002": "冲借款",*/}
                        <NCModal.Title >{multiLang && multiLang.get('201102BCLF-0057')}</NCModal.Title>
                    </NCModal.Header>

                    <NCModal.Body >
                        <div className="area-content" >
                            {/*<iframe src={window.location.protocol+"//"+window.location.host+"/erm/expenseaccount/adjustRelation/list/index.html"}*/}
                            {/*width="100%" className="relationmodel"></iframe>*/}
                            <AdjustRelationSearch showRelationModal={this.state.showRelationModal} setRelationChecked={this.setRelationChecked} />
                        </div>

                        <div>
                        </div>
                    </NCModal.Body>

                </NCModal>
                {/*联查单据*/}
                <NCModal
                    backdrop='static'
                    size="xlg"
                    show={
                        this.state.linkRelationBillModal
                    }
                    onHide={
                        () => {
                            this.setState({ linkRelationBillModal: false });
                        }
                    }
                >
                    {/*联查单据*/}
                    <NCModal.Header closeButton="true">
                        {/* 联查单据 */}
                        <NCModal.Title>{multiLang && multiLang.get('201102HKD-0003')}</NCModal.Title>
                    </NCModal.Header>
                    <NCModal.Body>

                        {createSimpleTable('linkrelationbill', {
                            onAfterEvent: afterEvent.bind(this),
                            showCheck: false,
                            showIndex: true,
                        })}
                    </NCModal.Body>
                    <NCModal.Footer></NCModal.Footer>
                </NCModal>
            </div>
        );

    }
}

Adjustment = createPage({
    mutiLangCode: '2011',
    billinfo: {
        billtype: 'card',  //虽然后台是一主多子数据结构，但是配置成extCard，编辑后请求公式验证会报错。因为会根据实际展现的表体数量来判断是一主多子还是一主一子。
        pagecode: presetVar.nccPageCode,
        headcode: head1,
        bodycode: body1
    },
    orderOfHotKey: [body1]
})(Adjustment);

export default Adjustment;
